#!/usr/bin/python3
# encoding=utf-8

import time
import RPi.GPIO

class GPIO():
    init_count = 0
    mode = RPi.GPIO.BCM

    def __init__(self, idx, init_with_output, init_with_high=False):
        self.idx = idx
        if idx is None:
            return

        if GPIO.init_count == 0:
            RPi.GPIO.setmode(GPIO.mode)
        GPIO.init_count += 1

        if init_with_output:  # 只有在输出的时候才可能会设置输出为高/低
            initial_status = RPi.GPIO.HIGH if init_with_high else RPi.GPIO.LOW
            RPi.GPIO.setup(idx, RPi.GPIO.OUT, initial=initial_status)
        else:
            RPi.GPIO.setup(idx, RPi.GPIO.IN)

    def __del__(self):
        if self.idx is None:
            return
        GPIO.init_count -= 1
        if GPIO.init_count == 0:
            RPi.GPIO.cleanup()

    def high(self):
        if self.idx is not None:
            RPi.GPIO.output(self.idx, RPi.GPIO.HIGH)

    def low(self):
        if self.idx is not None:
            RPi.GPIO.output(self.idx, RPi.GPIO.LOW)

    def input(self):
        if self.idx is not None:
            return RPi.GPIO.input(self.idx)


class PWM(GPIO):
    def __init__(self, idx, frequency):
        super(PWM, self).__init__(idx, init_with_output=True, init_with_high=False)
        self.pwm = RPi.GPIO.PWM(idx, frequency)
        self.pwm.start(0)

    def chanage_duty_cycle(self, cycle):
        self.pwm.ChangeDutyCycle(cycle)
        time.sleep(0.2)